package com.jjc.android.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.widget.CheckBox
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.allen.library.SuperButton
import com.hjq.toast.ToastUtils
import com.jjc.android.*
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.MessageImageDialog
import com.jjc.android.entity.LzyResponse
import com.jjc.android.entity.UserInfo
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.ComplexSpannableStringUtils
import com.jjc.android.util.GlobalActivityStack
import com.jjc.android.util.NoRefCopySpan
import com.jjc.android.util.paramEx
import com.jjc.android.view.CommonKt
import com.jjc.android.view.CountDownTextView
import com.jjc.android.view.onClick
import com.jjc.android.view.textChange
import com.lzy.okgo.OkGo
import com.xw.repo.XEditText

class RegisterActivity : BaseActivity(){

    companion object{
        fun start(context: Context,phone:String? = null){
            val intent = Intent(context,RegisterActivity::class.java)
            intent.putExtra("phone",phone)
            context.startActivity(intent)
        }
    }

    override val layoutId: Int = R.layout.activity_register
    private val versionNameTxt: TextView by lazy { findViewById<TextView>(R.id.versionNameTxt) }
    private val loginBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.loginBtn) }
    private val okBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.okBtn) }
    private val agreementCheckBox: CheckBox by lazy { findViewById<CheckBox>(R.id.agreementCheckBox) }
    private val rePasswordEt: XEditText by lazy { findViewById<XEditText>(R.id.rePasswordEt) }
    private val passwordEt: XEditText by lazy { findViewById<XEditText>(R.id.passwordEt) }
    private val sendOtpBtn: CountDownTextView by lazy { findViewById<CountDownTextView>(R.id.sendOtpBtn) }
    private val smsCodeEt: XEditText by lazy { findViewById<XEditText>(R.id.smsCodeEt) }
    private val phoneEt: XEditText by lazy { findViewById<XEditText>(R.id.phoneEt) }

    private var handlePhone:String? = null

    override fun initView(savedInstanceState: Bundle?) {
        setActivityTitle(getString(R.string.register_txt))
        sendOtpBtn.isEnabled = true
        if(!handlePhone.isNullOrEmpty()){
            phoneEt.setText(handlePhone)
        }
        agreementCheckBox.movementMethod = LinkMovementMethod()
        agreementCheckBox.text = ComplexSpannableStringUtils.getBuilder(getString(R.string.readed_agreed_txt))
            .append(getString(R.string.ag_hint_2_txt))
            .setForegroundColor(ContextCompat.getColor(this, R.color.c_831cb5))
            .setClickSpan(NoRefCopySpan {
                BrowserActivity.start(this, pageData = GlobalManager.getUserAgreementContent(), title = getString(R.string.user_ag_txt))
            })
            .append(getString(R.string.and_txt))
            .setForegroundColor(ContextCompat.getColor(this, R.color.colorPrimary))
            .append(getString(R.string.ag_hint_3_txt))
            .setForegroundColor(ContextCompat.getColor(this, R.color.c_831cb5))
            .setClickSpan(NoRefCopySpan {
                BrowserActivity.start(this, pageData = GlobalManager.getPrivacyPolicyContent(), title = getString(R.string.privacy_ag_txt))
            })
            .create()
        versionNameTxt.text = String.format("Va%d", BuildConfig.VERSION_CODE)
        loginBtn.onClick {
            startActivity(Intent(this,LoginActivity::class.java))
        }
        sendOtpBtn.onClick {
            if(phoneEt.text.toString().isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_phone_txt))
                return@onClick
            }
            if(!CommonKt.isPhoneValid(phoneEt.text.toString())){
                ToastUtils.show(getString(R.string.input_right_phone_txt))
                return@onClick
            }
            OkGo.get<LzyResponse<String>>(Constants.captchaSmsApp)
                .params(mapOf("phonenumber" to phoneEt.textEx))
                .tag(this@RegisterActivity)
                .execute(object : SimpleHttpCallback<LzyResponse<String>>(activity = this){
                    override fun onCallSuccess(response: LzyResponse<String>) {
                        sendOtpBtn.startCountDown()
                    }
                })
        }
        okBtn.onClick {
            if(phoneEt.text.toString().isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_phone_txt))
                return@onClick
            }
            if(!CommonKt.isPhoneValid(phoneEt.text.toString())){
                ToastUtils.show(getString(R.string.input_right_phone_txt))
                return@onClick
            }
            if(smsCodeEt.text.isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_sms_code_txt))
                return@onClick
            }
            if(!CommonKt.isSmsCodeValid(smsCodeEt.text.toString())){
                ToastUtils.show(getString(R.string.input_right_sms_code_txt))
                return@onClick
            }
            if(passwordEt.text.toString().isNullOrEmpty()){
                ToastUtils.show(getString(R.string.input_pwd_txt))
                return@onClick
            }
            if(rePasswordEt.text.toString().isNullOrEmpty()){
                ToastUtils.show(getString(R.string.re_input_pwd_txt))
                return@onClick
            }
            if(!CommonKt.isPasswordValid(passwordEt.text.toString())){
                ToastUtils.show(getString(R.string.re_input_right_pwd_txt))
                return@onClick
            }
            if(!CommonKt.isPasswordValid(rePasswordEt.text.toString())){
                ToastUtils.show(getString(R.string.re_input_right_pwd_again_txt))
                return@onClick
            }
            if(rePasswordEt.text.toString()!=passwordEt.text.toString()){
                ToastUtils.show(getString(R.string.pwd_not_same_txt))
                return@onClick
            }
            if(!agreementCheckBox.isChecked){
                ToastUtils.show(getString(R.string.read_agree_ag_txt))
                return@onClick
            }
            OkGo.post<LzyResponse<UserInfo>>(Constants.userRegister)
                .paramEx(mutableMapOf(
                    "username" to phoneEt.textEx,
                    "password" to passwordEt.textEx,
                    "confirmPassword" to rePasswordEt.textEx,
                    "code" to smsCodeEt.textEx,
                    "userType" to "app_user"
                ))
                .tag(this@RegisterActivity)
                .execute(object : SimpleHttpCallback<LzyResponse<UserInfo>>(activity = this){
                    override fun onCallSuccess(response: LzyResponse<UserInfo>) {
                        UserManager.loginSuccess(response.data.apply {
                            mobile = phoneEt.textEx
                        })
                        GlobalActivityStack.startAndFinishOthers(Intent(this@RegisterActivity,MainActivity::class.java))
                    }

//                    override fun onCallError(error: String?) {
//                        super.onCallError(error)
//                        if(!error.isNullOrEmpty()){
//                            MessageImageDialog.Builder(this@RegisterActivity)
//                                .imageResId(R.mipmap.alert_shibai_pic)
//                                .title("提示")
//                                .content(error)
//                                .cancleText(null)
//                                .okText("重新输入")
//                                .okClick {
//                                    if(error.contains("账号")||error.contains("手机号")){
//                                        phoneEt.setText("")
//                                    }else if(error.contains("验证码")) {
//                                        smsCodeEt.setText("")
//                                    }else if(error.contains("密码")) {
//                                        passwordEt.setText("")
//                                    }
//                                }
//                                .build()
//                                .show()
//                        }
//                    }
                })
        }
    }

    override fun setupArguments(args: Bundle?) {
        handlePhone = args?.getString("phone")
    }
}